﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace RAP.Framework.Libary.Utils
{
    /// <summary>
    /// 
    /// </summary>
    public static partial class Extensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="func"></param>
        /// <param name="timeout">执行超时时间（ms）</param>
        /// <param name="onTimeout">执行超时时的回调</param>
        /// <param name="interval">再次执行的延迟时间（ms）</param>
        public static void Timeout( this Func<bool> func, int timeout, Action onTimeout = null, int interval = 10 )
        {
            if ( func == null )
            {
                return;
            }

            Task.Run( ( ) =>
            {
                if ( timeout <= 0 )
                {
                    func( );
                    return;
                }
                DateTime start = DateTime.Now;
                double duration = 0;
                bool result = false;
                while ( !result && duration < timeout )
                {
                    //如果func返回false，则继续执行，当func返回true时结束执行
                    result = func( );
                    Thread.Sleep( interval );
                    duration = DateTime.Now.Subtract( start ).TotalMilliseconds;
                }
                if ( !result && duration >= timeout )
                {
                    if ( onTimeout != null )
                    {
                        onTimeout( );
                    }
                }
            } );
        }

        /// <summary>
        /// 将指定Action运行在线程当中
        /// </summary>
        /// <param name="action"></param>
        public static void RunInThread( this Action action )
        {
            ( new Thread( new ThreadStart( action ) ) { IsBackground = true } ).Start( );
        }
    }
}
